// 添加缺失的 React 和 useState 导入
import React, { useState, useEffect } from 'react'
import {
  DownloadOutlined,
  GiftOutlined,
  PlusOutlined,
  ThunderboltOutlined,
  MoneyCollectOutlined,
  ShoppingOutlined,
  TeamOutlined
} from '@ant-design/icons'
import { regionData } from '../utils/region'
import {
  Button,
  Col,
  Flex,
  Form,
  Input,
  Row,
  Select,
  Typography,
  Table,
  Alert,
  Cascader,
  Switch,
  Modal,
  Divider,
  message
} from 'antd'
import MyDatePicker from '../components/MyDatePicker'
import { Link, useNavigate } from 'react-router-dom'
// 首先确保导入了所有需要的函数，包括删除活动的函数 
import { adminActivatyList, adminActivatyStatus, adminActivatyEdit, adminActivatyDelete } from '../service/activaty'

export default function MarketActivaty() {
  const navigate = useNavigate()
  // 保存选择的日期
  const [selectedDateString, setSelectedDateString] = useState(null)
  // 保存店铺列表
  const [storeList, setStoreList] = useState([])
  // 保存页码
  const [pageNo, setPageNo] = useState(1)
  // 总数据量
  const [total, setTotal] = useState(0)
  // 添加搜索条件状态
  const [condition, setCondition] = useState({})
  // 预设日期
  // 保存表格中选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 表格中是否有选中
  const hasSelected = selectedRowKeys.length > 0
  // 模态框
  const [isModalOpen, setIsModalOpen] = useState(false)
  // 获取省市区选中的值
  const regionChange = (value) => {
    console.log(value)
  }
  // 活动选项列表
  const activeList = [
    {
      index: 0,
      icon: <TeamOutlined />,
      title: '赠领'
    },
    {
      index: 1,
      icon: <ShoppingOutlined />,
      title: '拼团'
    },
    {
      index: 2,
      icon: <ThunderboltOutlined />,
      title: '秒杀'
    },
    {
      index: 3,
      icon: <MoneyCollectOutlined />,
      title: '返现'
    },
    {
      index: 4,
      icon: <GiftOutlined />,
      title: '抽奖'
    }
  ]
  // 默认选中的下标
  const [selectedIndex, setSelectedIndex] = useState(null)
  // 用于更新列表
  const [n, setN] = useState(1)
  // 修改request函数，使其接收搜索条件
  const request = async (searchCondition = {}) => {
    try {
      const res = await adminActivatyList({
        ...condition,
        ...searchCondition,
        pageNo,
        pageSize: 10
      })
      console.log(res)
      if (res?.data) {
        setStoreList(res.data.objects || [])
        setTotal(res.data.total || 0)
      } else {
        // 处理接口返回异常
        setStoreList([])
        setTotal(0)
      }
    } catch (error) {
      console.error('获取活动列表失败:', error)
      message.error('获取活动列表失败，请稍后重试')
      setStoreList([])
      setTotal(0)
    }
  }
  useEffect(() => {
    request()
  }, [n, pageNo])

  return (
      <>
        <Row className="info">
          <Col span={24}>
            <Flex justify={'space-between'}>
              <Typography.Title level={3}>信息管理</Typography.Title>
              <Button
                  type="primary"
                  icon={<PlusOutlined />}
                  onClick={() => setIsModalOpen(true)}
              >
                新建活动
              </Button>
            </Flex>
          </Col>
        </Row>
        <Row className="container">
          <Col span={24}>
            <Form
                // layout="inline"
                onFinish={async (values) => {
                  console.log(values)
                  // 保存搜索条件
                  setCondition(values)
                  // 重新获取数据
                  await request(values)
                }}
            >
              <Row>
                <Col span={6} className="myinput">
                  <Form.Item label="活动标题：" name="activityName">
                    <Input placeholder="请输入活动标题" />
                  </Form.Item>
                </Col>
                <Col span={6} className="myinput">
                  <Form.Item label="活动类型：" name="activityType">
                    <Select
                        placeholder="类型选择"
                        // style={{ width: 200 }}
                        options={[
                          {
                            value: '',
                            label: '全部'
                          },
                          {
                            value: '0',
                            label: '赠领'
                          },
                          {
                            value: '1',
                            label: '拼团'
                          },
                          {
                            value: '2',
                            label: '抽奖'
                          },
                          {
                            value: '3',
                            label: '砍一刀'
                          }
                        ]}
                    />
                  </Form.Item>
                </Col>
                <Col span={6} className="myinput">
                  <Form.Item label="活动渠道：" name="channelType">
                    <Select
                        placeholder="渠道选择"
                        // style={{ width: 200 }}
                        options={[
                          {
                            value: '',
                            label: '全部'
                          },
                          {
                            value: '0',
                            label: 'APP'
                          }
                        ]}
                    />
                  </Form.Item>
                </Col>
                <Col span={6} className="myinput">
                  <Form.Item label="活动状态：" name="status">
                    <Select
                        placeholder="请选择活动状态"
                        // style={{ width: 200 }}
                        options={[
                          {
                            value: '',
                            label: '全部'
                          },
                          {
                            value: '0',
                            label: '未开始'
                          },
                          {
                            value: '1',
                            label: '进行中'
                          },
                          {
                            value: '2',
                            label: '已结束'
                          }
                        ]}
                    />
                  </Form.Item>
                </Col>
              </Row>
              <Row>
                <Col span={6} className="myinput">
                  <Form.Item label="营销方式：" name="marketingType">
                    <Select
                        placeholder="请选择营销方式"
                        // style={{ width: 200 }}
                        options={[
                          {
                            value: '',
                            label: '全部'
                          },
                          {
                            value: '0',
                            label: '内容推送'
                          },
                          {
                            value: '1',
                            label: '消息推送'
                          }
                        ]}
                    />
                  </Form.Item>
                </Col>
                <Col span={6} className="myinput">
                  <Form.Item label="活动时间">
                    <MyDatePicker
                        selectedDateString={selectedDateString}
                        setSelectedDateString={setSelectedDateString}
                    />
                  </Form.Item>
                </Col>
                <Col span={6} className="myinput">
                  <Form.Item label="区域选择：" name="storeAddress">
                    <Cascader
                        options={regionData}
                        onChange={regionChange}
                        placeholder="请选择查询的省/市/区县"
                        style={{ width: 280 }}
                    />
                  </Form.Item>
                </Col>
                <Col span={2} className="myinput">
                  <Form.Item>
                    <Button type="default" htmlType="reset">
                      重置
                    </Button>
                  </Form.Item>
                </Col>
                <Col span={1} className="myinput">
                  <Form.Item>
                    <Button type="primary" htmlType="submit">
                      查询
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Col>
        </Row>
        <Row className="container">
          <Col span={24}>
            <Typography.Paragraph style={{ fontSize: 16 }}>
              活动列表
            </Typography.Paragraph>
            {hasSelected && (
                <Alert
                    message={`已经选择 ${selectedRowKeys.length} 项`}
                    type="info"
                    showIcon
                />
            )}
          </Col>
          <Col span={24}>
            <Table
                pagination={{
                  total,
                  defaultCurrent: 1,
                  onChange: async (page) => {
                    setPageNo(page)
                  }
                }}
                rowKey="id"
                rowSelection={{
                  selectedRowKeys,
                  onChange: (newSelectedRowKeys) => {
                    console.log('selectedRowKeys changed: ', newSelectedRowKeys)
                    setSelectedRowKeys(newSelectedRowKeys)
                  }
                }}
                dataSource={storeList}
                columns={[
                  {
                    title: '编号',
                    dataIndex: 'id',
                    key: 'id'
                  },
                  {
                    title: '活动标题',
                    dataIndex: 'activityName',
                    key: 'activityName'
                  },
                  {
                    title: '活动目标',
                    dataIndex: 'activityTarget',
                    key: 'activityTarget'
                  },
                  {
                    title: '活动类型',
                    dataIndex: 'activityType',
                    key: 'activityType',
                    render: (_, record) => {
                      const typeMap = {
                        0: '赠领',
                        1: '拼团',
                        2: '抽奖',
                        3: '砍一刀'
                      }
                      return typeMap[record.activityType] || '未知'
                    }
                  },
                  {
                    title: '活动奖励',
                    dataIndex: 'couponName',
                    key: 'rewardCouponId'
                  },
                  {
                    title: '店铺',
                    dataIndex: 'shopIds',
                    key: 'shopIds',
                    render: (_, record) => {
                      // 获取店铺数量
                      return <>数量（{record.shopIds?.split(',').length || 0}）</>
                    }
                  },
                  {
                    title: '渠道',
                    dataIndex: 'channelType',
                    key: 'channelType',
                    render: (_, record) => {
                      return (
                          <>
                            {record.channelType === 0 && '全部'}
                            {record.channelType === 1 && 'APP'}
                            {record.channelType === 2 && '小程序'}
                          </>
                      )
                    }
                  },
                  {
                    title: '营销方式',
                    dataIndex: 'marketingType',
                    key: 'marketingType',
                    render: (_, record) => {
                      return (
                          <>
                            {record.marketingType === 0 && '全部'}
                            {record.marketingType === 1 && '内容推送'}
                            {record.marketingType === 2 && '消息推送'}
                          </>
                      )
                    }
                  },
                  {
                    title: '活动时间',
                    dataIndex: 'storeStatus',
                    key: 'storeStatus',
                    render: (_, record) => {
                      return (
                          <>
                            {record.startDate} - {record.endDate}
                          </>
                      )
                    }
                  },
                  {
                    title: '活动状态',
                    dataIndex: 'status',
                    key: 'status',
                    render: (_, record) => (
                        <Switch
                            defaultChecked={record.status === 1}
                            onChange={async (value) => {
                              try {
                                const res = await adminActivatyStatus({
                                  id: record.id,
                                  status: value ? 1 : 0
                                })
                                console.log('更新活动状态响应:', res)
                                message.success(value ? '开启成功' : '关闭成功')
                              } catch (error) {
                                console.error('更新活动状态失败:', error);
                                console.error('请求参数:', { id: record.id, status: value ? 1 : 0 });
                                // 增加更详细的错误信息提示
                                if (error.response) {
                                  message.error(`${value ? '开启失败' : '关闭失败'}: ${error.response.status} - ${error.response.data?.message || error.response.statusText}`);
                                } else {
                                  message.error(value ? '开启失败' : '关闭失败');
                                }
                              }
                            }}
                        />
                    )
                  },
                  {
                    title: '操作',
                    dataIndex: 'op',
                    key: 'op',
                    align: 'center',
                    render: (_, record) => {
                      return (
                          <span className="op">
                      <Link to={`/admin/market/editActivaty/${record.id}`}>
                        编辑
                      </Link>
                      <a
                          style={{ marginLeft: 10 }}
                          onClick={async () => {
                            try {
                              Modal.confirm({
                                title: '确认删除',
                                content: `确定要删除活动"${record.activityName}"吗？`,
                                onOk: async () => {
                                  try {
                                    const res = await adminActivatyDelete(record.id)
                                    if (res?.code === '0') {
                                      message.success('活动删除成功')
                                      setN(n + 1)
                                    } else {
                                      message.error('活动删除失败：' + (res?.msg || '未知错误'))
                                    }
                                  } catch (error) {
                                    console.error('删除活动失败:', error)
                                    message.error('删除活动失败，请稍后重试')
                                  }
                                }
                              })
                            } catch (error) {
                              console.error('删除活动确认失败:', error)
                            }
                          }}
                      >
                        删除
                      </a>
                    </span>
                      )
                    }
                  }
                ]}
            />
          </Col>
        </Row>
        <Modal
            title="选择活动"
            open={isModalOpen}
            maskClosable={false}
            width={750}
            destroyOnClose
            footer={null}
            onCancel={() => setIsModalOpen(false)}
        >
          <Divider />

          <div className="active-list">
            {activeList.map((item, index) => (
                <div
                    key={index}
                    className={selectedIndex === index ? 'selected' : ''}
                    onClick={() => setSelectedIndex(index)}
                >
              <span>
                <span className="icon">{item.icon}</span>
                <span>{item.title}</span>
              </span>
                </div>
            ))}
          </div>
          <Flex justify="center" align="center" style={{ marginTop: 30 }}>
            <Button
                type="primary"
                size="large"
                style={{ padding: '0 40px' }}
                onClick={() => navigate('/admin/market/addActivaty')}
            >
              新建活动
            </Button>
          </Flex>
        </Modal>
      </>
  )
}